<template src="./template.html"></template>
<script>
import { FUN_IDS_OPTIONS } from 'common/consts'
import CourseMixins from '../mixins'
import { getLessonFindList, publishLesson, unPublishLesson, deleteLesson } from './models'

export default {
  mixins: [CourseMixins],
  data() {
    return {
      FUN_IDS_OPTIONS,
      periodList: [],
      isLoading: false
    }
  },
  methods: {
    $handleAdd() {
      this.$router.push({
        name: 'curriculum.manager.add-period',
        params: {
          courseId: this.courseId
        }
      })
    },
    $handleEdit(it) {
      this.$router.push({
        name: 'curriculum.manager.edit-period',
        params: {
          courseId: this.courseId,
          id: it.id
        }
      })
    },
    async $getLessonFindList() {
      this.isLoading = true
      const params = {
        courseId: this.courseId
      }
      try {
        const { data } = await getLessonFindList(params)
        this.periodList = (data || []).map(it => ({
          ...it,
          practiceProject: it.practiceProject ? it.practiceProject.split(',') : []
        }))
        this.isLoading = false
      } catch (err) {
        this.isLoading = false
        this.$message.error(err.message || '获取信息出错')
      }
    },
    async $handleSwitch(newVal, id) {
      this.isLoading = true
      let fun = unPublishLesson
      if (parseInt(newVal, 10) === 1) {
        fun = publishLesson
      }
      const params = {
        id: id
      }
      try {
        await fun(params)
        let tips = '课时已取消发布！'
        if (parseInt(newVal, 10) === 1) {
          tips = '课时发布成功！！'
        }
        this.$message.success(tips)
        this.isLoading = false
      } catch (err) {
        this.$message.error(err.message || '操作失败')
        this.isLoading = false
      }
    },
    // 删除请求
    async $handleDeleteHttp(params) {
      try {
        this.isLoading = true
        await deleteLesson(params)
        this.$message.success('课时删除成功！')
        this.$getLessonFindList()
      } catch (err) {
        this.isLoading = false
        this.$message.error(err.retDesc || err.message || '删除出错')
      }
    },
    // 删除点击
    $handleDelete(row) {
      const params = {
        lessonId: row.id
      }
      this.$confirm('是否确认删除该课时？', {
        type: 'warning',
        confirmButtonText: '删除',
      }).then(() => {
        this.$handleDeleteHttp(params)
      }).catch(() => {
        console.log('取消');
      });
    },
  },
  mounted() {
    this.$getLessonFindList()
  }
}
</script>
